package com.freecloud.whispered.oss;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.freecloud.framework.constant.ConfigConstant;
import com.freecloud.framework.constant.Constant;
import com.freecloud.framework.utils.SpringContextUtils;
import com.freecloud.whispered.oss.config.CloudStorageConfig;
import com.freecloud.whispered.oss.service.AliyunCloudStorageService;
import com.freecloud.whispered.oss.service.CloudStorageService;
import com.freecloud.whispered.oss.service.QcloudCloudStorageService;
import com.freecloud.whispered.oss.service.QiniuCloudStorageService;
import com.freecloud.whispered.system.service.SysConfigCallFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * 文件上传Factory
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-03-26 10:18
 */
@Component
public final class OSSFactory {

    private static Logger logger = LoggerFactory.getLogger(OSSFactory.class);

    public static CloudStorageService build(){

        SysConfigCallFactory sysConfigCallFactory = SpringContextUtils.getBean(SysConfigCallFactory.class);

        //获取云存储配置信息
        String confiString = sysConfigCallFactory.call().getValue(ConfigConstant.CLOUD_STORAGE_CONFIG_KEY,"");
        if(StrUtil.isBlank(confiString)){
            logger.error("获取oss config配置信息错误！结果为空！");
            return null;
        }else if(!JSONUtil.isJson(confiString)){
            logger.error("获取oss config配置信息错误：{}",confiString);
            return null;
        }

        CloudStorageConfig config = JSONUtil.parseObj(confiString).toBean(CloudStorageConfig.class);

        if(config.getType() == Constant.CloudService.QINIU.getValue()){
            return new QiniuCloudStorageService(config);
        }else if(config.getType() == Constant.CloudService.ALIYUN.getValue()){
            return new AliyunCloudStorageService(config);
        }else if(config.getType() == Constant.CloudService.QCLOUD.getValue()){
            return new QcloudCloudStorageService(config);
        }
        return null;
    }

}
